# 给你一个 m 行 n 列的矩阵 matrix ，请按照 顺时针螺旋顺序 ，返回矩阵中的所有元素。 
# 
#  
# 
#  示例 1： 
#  
#  
# 输入：matrix = [[1,2,3],[4,5,6],[7,8,9]]
# 输出：[1,2,3,6,9,8,7,4,5]
#  
# 
#  示例 2： 
#  
#  
# 输入：matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
# 输出：[1,2,3,4,8,12,11,10,9,5,6,7]
#  
# 
#  
# 
#  提示： 
# 
#  
#  m == matrix.length 
#  n == matrix[i].length 
#  1 <= m, n <= 10 
#  -100 <= matrix[i][j] <= 100 
#  
# 
#  Related Topics 数组 矩阵 模拟 👍 1807 👎 0
from typing import List


# leetcode submit region begin(Prohibit modification and deletion)
class Solution:
    def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
        """
        思路：每旋转一圈，就缩圈（每跑完一条边就锁小对应的边界范围）直到边界出现交叉时停止循环
        :param matrix:
        :return:
        """
        m = len(matrix)
        n = len(matrix[0])
        left = i = j = 0  # 最左边界
        right = n - 1  # 最右边界
        top = 0  # 最上边界
        bottom = m - 1  # 最下边界
        re = [matrix[0][0]]
        direction='right'
        while top<=bottom and left<=right:
            if direction=='right':
                temp = j
                for j1 in range(temp+1,right+1):
                    j =j1

                    re.append(matrix[i][j])
                top+=1
                direction='bottom'
                continue

            if direction== 'bottom':
                temp = i
                for i1 in range(temp+1,bottom+1):
                    i = i1
                    re.append(matrix[i][j])
                right -= 1
                direction = 'left'
                continue

            if direction== 'left':
                temp = j
                for j1 in range(temp-1,left-1,-1):
                    j = j1
                    re.append(matrix[i][j])
                bottom -= 1
                direction = 'top'
                continue

            if direction== 'top':
                temp = i
                for i1 in range(temp-1,top-1,-1):
                    i = i1
                    re.append(matrix[i][j])
                left += 1
                direction = 'right'
                continue

        return re

        
# leetcode submit region end(Prohibit modification and deletion)
print(Solution().spiralOrder(matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]))